package cn.mengfly.fxtest.app.dialog;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.util.Optional;


/**
 * @author Mengfly
 */
public class DialogApp extends Application {
    private final TextField dbURL = new TextField();

    private final ConnectionInfoStringConverter ciConverter = new ConnectionInfoStringConverter();

    @Override
    public void start(Stage primaryStage) throws Exception {
        Label label = new Label("Db Url");
        dbURL.setPrefWidth(400d);

        Button btn = new Button("Set");
        btn.setOnAction(this::showSetDialog);

        VBox box = new VBox(label, dbURL, btn);
        box.setSpacing(10);
        box.setPadding(new Insets(40d));

        Scene scene = new Scene(box);

        primaryStage.setTitle("Dialog App");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void showSetDialog(ActionEvent event) {
        ConnectionInfo fromUrl = ciConverter.fromString(dbURL.getText());

        ConnectionDialog dialog = new ConnectionDialog(fromUrl);

        Optional<ConnectionInfo> ci = dialog.showAndWait();

        ci.ifPresent(connectionInfo -> dbURL.setText(ciConverter.toString(connectionInfo)));
    }

    final static class ConnectionInfoStringConverter extends StringConverter<ConnectionInfo> {
        private final String format = "%s@%s:%s";

        @Override
        public String toString(ConnectionInfo c) {
            return String.format(format, c.getUsername(), c.getPassword(), c.getHost());
        }

        @Override
        public ConnectionInfo fromString(String s) {
            if( s != null && s.contains("@") && s.contains(":") ) {
               String[] toks = s.split("@");
               String username = toks[0];
               String[] secondPart = toks[1].split(":");
               String password = secondPart[0];
               String host = secondPart[1];
               ConnectionInfo ci = new ConnectionInfo(
                        username, password, host);
               return ci;
           }

           return null;
        }
    }
}
